package cn.geminis.crypto.tsp;

import org.bouncycastle.asn1.ASN1Encoding;
import org.bouncycastle.asn1.BERSequence;
import org.bouncycastle.tsp.TSPException;

import java.io.IOException;

/**
 * @author Allen
 */
public class TimeStampResponse {

    private org.bouncycastle.tsp.TimeStampResponse bcResponse;

    TimeStampResponse(org.bouncycastle.tsp.TimeStampResponse bcResponse) {
        this.bcResponse = bcResponse;
    }

    public TimeStampResponse(byte[] data) {
        try {
            bcResponse = new org.bouncycastle.tsp.TimeStampResponse(data);
        } catch (Exception e) {
            throw new RuntimeException("解析时间戳响应错误", e);
        }
    }

    public org.bouncycastle.tsp.TimeStampResponse getBcResponse() {
        return this.bcResponse;
    }

    public byte[] getEncode() {
        try {
            return bcResponse.getEncoded();
        } catch (IOException e) {
            throw new RuntimeException("DER格式编码错误", e);
        }
    }

    public byte[] getTokenEncode() {
        try {
            byte[] berData = bcResponse.getTimeStampToken().getEncoded();
            return BERSequence.fromByteArray(berData).getEncoded(ASN1Encoding.DER);
        } catch (IOException e) {
            throw new RuntimeException("DER格式编码错误", e);
        }
    }

    public void verify(TimeStampRequest request) {
        try {
            bcResponse.validate(request.getBcRequest());
            if (bcResponse.getStatus() != 0) {
                throw new RuntimeException("时间戳响应异常，状态值：" + bcResponse.getStatus() + "，原因：" + bcResponse.getStatusString());
            }
        } catch (TSPException e) {
            throw new RuntimeException("验证时间戳响应错误", e);
        }
    }

    public TimeStampToken getToken() {
        return new TimeStampToken(this.bcResponse.getTimeStampToken());
    }

}
